<template>
  <div class="console">
    <!--导航卡片-->
    <div class="mt-4">
      <!-- 货物类型和日期类型下拉框 -->
      <NRow :gutter="24" class="mb-4">
        <NCol :span="4">
          <n-form-item label="货物类型：" label-placement="left">
            <n-select
              v-model:value="selectedGoodsType"
              :options="goodsTypeOptions"
              placeholder="请选择货物"
              filterable
              @change="handleGoodsTypeChange"
            />
          </n-form-item>
        </NCol>
        <NCol :span="4">
          <n-form-item label="日期类型：" label-placement="left">
            <n-select
              v-model:value="selectedDateType"
              :options="dateTypeOptions"
              placeholder="请选择日期类型"
              @change="handleDateTypeChange"
            />
          </n-form-item>
        </NCol>
      </NRow>
      <!-- 修改为在所有屏幕尺寸下都占据全部宽度 -->
      <NRow :gutter="24">
      <NCol :span="24">
        <n-card content-style="padding: 0;" :bordered="false">
         <div ref="lineChartRef" :style="{ height: '400px', width: '100%' }"></div>
        </n-card>
      </NCol>
      </NRow>
      
      <!-- 第二个折线图 -->
      <NRow :gutter="24" class="mt-8" style="margin-top: 20px;">
      <NCol :span="24">
        <n-card content-style="padding: 0;" :bordered="false">
         <div ref="secondLineChartRef" :style="{ height: '400px', width: '100%' }"></div>
        </n-card>
      </NCol>
      </NRow>
    </div>

    <!--访问量 | 流量趋势-->
    <!-- <VisiTab :selectedGoodsType="selectedGoodsType" /> -->
  </div>
</template>
<script lang="ts" setup>
    import { ref, onMounted, reactive, Ref } from 'vue';
    import { getGoodsType,getPastFiveYearGoodsTypePrice,getPastFiveYearGoodsTypeWeight } from '@/api/weight/goodsType';
    import { useECharts } from '@/hooks/web/useECharts';

  const loading = ref(true);

  // getCurrentDayGoodsWeight接口返回值类型定义
  interface GoodsWeightItem {
    dateStr: string;
    year: string;
    weightSum:number;
  }

    interface GoodsPriceItem {
    dateStr: string;
    year: string;
    goodsPrice:number;
  }


  const priceLastSevenGoodsData = ref<GoodsPriceItem[]>([]);

  const weightLastSevenGoodsData = ref<GoodsWeightItem[]>([]);
  
  // 存储当前选中的商品类型，用于同步更新VisiTab组件
  const selectedGoodsType = ref<number | null>(null);
  // 存储货物类型选项
  const goodsTypeOptions = ref<any[]>([]);
  // 存储当前选中的日期类型，默认选择日
  const selectedDateType = ref<string>('日');
  // 存储日期类型选项
  const dateTypeOptions = ref([
    { label: '日', value: '日' },
    { label: '周', value: '周' },
    { label: '月', value: '月' }
  ]);
  
  // 处理日期类型变化
  const handleDateTypeChange = async (value: string) => {
    console.log('日期类型已更改为:', value);
    // 如果当前已经有选中的货物类型，则重新获取数据
    if (currentGoodsTypeId.value !== null) {
      try {
        const trendData = await getPastFiveYearGoodsTypePrice(currentGoodsTypeId.value, value);
        updateLineChart(trendData);
         const weightTrendData = await getPastFiveYearGoodsTypeWeight(currentGoodsTypeId.value, value);
        updateSecondLineChart(weightTrendData);
      } catch (error) {
          console.error('切换日期类型时获取数据失败:', error);
          updateLineChart([]);
          updateSecondLineChart([]);
        }
    }
  };
  // 当前选中的货物类型ID
  const currentGoodsTypeId = ref<number | null>(null);
  // 曲线图容器引用
  const lineChartRef = ref<HTMLDivElement | null>(null);
  const { setOptions: setLineChartOptions } = useECharts(lineChartRef as Ref<HTMLDivElement>);
  
  // 第二个曲线图容器引用
  const secondLineChartRef = ref<HTMLDivElement | null>(null);
  const { setOptions: setSecondLineChartOptions } = useECharts(secondLineChartRef as Ref<HTMLDivElement>);
  
  // 更新第二个折线图的函数
  function updateSecondLineChart(data: GoodsWeightItem[]) {
    if (!data || !Array.isArray(data)) {
      data = [];
    }
    
    const hasData = data.length > 0 && data.some(d => d.weightSum > 0)

    const goodsNames = [...new Set(data.map(d => d.year))]
    // 获取所有日期
    const dates = [...new Set(data.map(d => d.dateStr))];

    const colors = ['#69c0ff', '#ff9c6e', '#5cdbd3', '#b37feb', '#ff6700', '#006400']

    const series = hasData
      ? goodsNames.map((name, idx) => {
          const color = colors[idx % colors.length]
          return {
            name, 
            type: 'line' as const,
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            data: dates.map(date => {
              const item = data.find(d => d.year === name && d.dateStr === date)
              return item ? item.weightSum : null
            }),
            lineStyle: { width: 3, color },
            itemStyle: { color },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [
                  { offset: 0, color: `${color}44` },
                  { offset: 1, color: `${color}05` }
                ]
              }
            }
          }
        })
      : [
          {
            name: '暂无数据',
            type: 'line' as const,
            data: [0],
            lineStyle: { color: '#ccc' },
            itemStyle: { color: '#ccc' },
            areaStyle: { color: '#f5f5f5' }
          }
        ]

    const finalDates = hasData ? dates : ['暂无数据']

    const option = {
      title: {
        text: hasData ? '近五年重量趋势' : '暂无重量数据',
        left: 'center',
        textStyle: { fontSize: 16, fontWeight: 'normal' }
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params: any) => {
          const date = params[0]?.axisValue
          let res = `${date}<br/>`
          params.forEach((p: any) => {
            res += `${p.marker}${p.seriesName}: ${p.value} KG<br/>`
          })
          return res
        }
      },
      legend: { data: series.map(s => s.name), top: '30px' },
      grid: { left: '3%', right: '4%', bottom: '3%', top: '80px', containLabel: true },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: finalDates,
        axisLabel: {
          formatter: (val: string) => val
        }
      },
      yAxis: {
        type: 'value',
        name: '重量 (KG)',
        axisLabel: { formatter: '{value} KG' }
      },
      series
    }
    
    // 设置图表选项
    setSecondLineChartOptions(option);
  }
 
// 更新折线图的函数
  function updateLineChart(data: GoodsPriceItem[]) {
    if (!data || !Array.isArray(data)) {
      data = [];
    }
    
    const hasData = data.length > 0 && data.some(d => d.goodsPrice > 0)

    const goodsNames = [...new Set(data.map(d => d.year))]
    // 获取所有日期
    // 不使用日期解析进行排序，直接使用原始顺序或简单的字符串排序
    const dates = [...new Set(data.map(d => d.dateStr))];

    const colors = ['#69c0ff', '#ff9c6e', '#5cdbd3', '#b37feb', '#ff6700', '#006400']

    const series = hasData
      ? goodsNames.map((name, idx) => {
          const color = colors[idx % colors.length]
          return {
            name,
            type: 'line' as const,
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            data: dates.map(date => {
              const item = data.find(d => d.year === name && d.dateStr === date)
              return item ? item.goodsPrice : null
            }),
            lineStyle: { width: 3, color },
            itemStyle: { color },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [
                  { offset: 0, color: `${color}44` },
                  { offset: 1, color: `${color}05` }
                ]
              }
            }
          }
        })
      : [
          {
            name: '暂无数据',
            type: 'line' as const,
            data: [0],
            lineStyle: { color: '#ccc' },
            itemStyle: { color: '#ccc' },
            areaStyle: { color: '#f5f5f5' }
          }
        ]

    const finalDates = hasData ? dates : ['暂无数据']

    const option = {
      title: {
        text: hasData ? '近五年货物单价趋势' : '暂无价格数据',
        left: 'center',
        textStyle: { fontSize: 16, fontWeight: 'normal' }
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params: any) => {
          const date = params[0]?.axisValue
          let res = `${date}<br/>`
          params.forEach((p: any) => {
            res += `${p.marker}${p.seriesName}: ${p.value} 元<br/>`
          })
          return res
        }
      },
      legend: { data: series.map(s => s.name), top: '30px' },
      grid: { left: '3%', right: '4%', bottom: '3%', top: '80px', containLabel: true },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: finalDates,
        axisLabel: {
          formatter: (val: string) => val
        }
      },
      yAxis: {
        type: 'value',
        name: '单价 (元)',
        axisLabel: { formatter: '{value} 元' }
      },
      series
    }
    
    // 设置图表选项
    setLineChartOptions(option);
  }

  // 加载货物类型数据
  const loadGoodsTypes = async () => {
    try {
      const goodsTypeResult = await getGoodsType();
      console.log('获取货物类型数据结果:', goodsTypeResult);
      
      // 检查响应是否有效
      if (!goodsTypeResult) {
        console.error('获取货物类型数据失败: 响应为空');
        return;
      }
      
      // 尝试不同的响应数据结构处理
      let goodsTypeList = [];
      
      // 处理标准格式响应 {code, message, result}
      if (goodsTypeResult.result && Array.isArray(goodsTypeResult.result)) {
        goodsTypeList = goodsTypeResult.result;
      }
      // 处理直接返回数组的情况
      else if (Array.isArray(goodsTypeResult)) {
        goodsTypeList = goodsTypeResult;
      }
      
      // 转换为select组件需要的格式
      if (goodsTypeList.length > 0) {
        goodsTypeOptions.value = goodsTypeList.map((item: any) => ({
          label: item.goodsName || item.name || '未知商品',
          value: item.id || item.goodsType || Math.random() // 确保有value
        }));
        console.log('转换后的下拉框选项:', goodsTypeOptions.value);
      } else {
        console.warn('未获取到有效货物类型数据');
        // 添加一些默认选项以便测试
        goodsTypeOptions.value = [
          { label: '测试商品1', value: 1 },
          { label: '测试商品2', value: 2 }
        ];
      }
    } catch (error) {
      console.error('获取货物类型数据失败:', error);
      // 发生错误时添加默认选项
      goodsTypeOptions.value = [
        { label: '测试商品1', value: 1 },
        { label: '测试商品2', value: 2 }
      ];
    }
  };

  // 处理货物类型变化
  const handleGoodsTypeChange = async (value: number | null) => {
    currentGoodsTypeId.value = value;
    if (value !== null) {
      try {
        // 根据选中的货物类型和日期类型获取价格趋势数据
        console.log('获取价格趋势数据参数:', { goodsType: value, dateType: selectedDateType.value });
        const trendData = await getPastFiveYearGoodsTypePrice(value, selectedDateType.value);
        // 更新两个折线图
        updateLineChart(trendData);
        const weightTrendData = await getPastFiveYearGoodsTypeWeight(value, selectedDateType.value);
        updateSecondLineChart(weightTrendData);
      } catch (error) {
        console.error('获取价格趋势数据失败:', error);
        updateLineChart([]);
        updateSecondLineChart([]);
      }
    } else {
      // 如果未选择任何货物类型，显示第一个可用货物类型的价格趋势
      const defaultGoodsTypeId = goodsTypeOptions.value.length > 0 ? goodsTypeOptions.value[0].value : null;
      if (defaultGoodsTypeId) {
        const goodsPriceResult = await getPastFiveYearGoodsTypePrice(defaultGoodsTypeId, selectedDateType.value);
        if (goodsPriceResult && goodsPriceResult.result && Array.isArray(goodsPriceResult.result)) {
          updateLineChart(goodsPriceResult.result);
        }
        const weightTrendData = await getPastFiveYearGoodsTypeWeight(defaultGoodsTypeId, selectedDateType.value);
        if (weightTrendData && weightTrendData.result && Array.isArray(weightTrendData.result)) {
          updateSecondLineChart(weightTrendData.result);
        }
      }
    }
  };

  onMounted(async () => {
    try {
      // 加载货物类型数据
      await loadGoodsTypes();
      
      // 获取默认的货物类型ID
      const defaultGoodsTypeId = goodsTypeOptions.value.length > 0 ? goodsTypeOptions.value[0].value : null;
      
      if (defaultGoodsTypeId) {
        // 先设置默认选中的货物类型，确保下拉框能正确显示选中状态
        selectedGoodsType.value = defaultGoodsTypeId;
        currentGoodsTypeId.value = defaultGoodsTypeId;
        console.log('已设置默认选中的货物类型ID:', defaultGoodsTypeId);
        
        // 调用商品近5年价格数据，传递默认的货物类型ID和日期类型
        const goodsPriceResult = await getPastFiveYearGoodsTypePrice(defaultGoodsTypeId, selectedDateType.value);
        if (goodsPriceResult) {
          if (goodsPriceResult.result && Array.isArray(goodsPriceResult.result)) {
            priceLastSevenGoodsData.value = goodsPriceResult.result;
          } else if (Array.isArray(goodsPriceResult)) {
            priceLastSevenGoodsData.value = goodsPriceResult;
          }
        }
         // 调用updateLineChart函数来更新图表
        updateLineChart(priceLastSevenGoodsData.value);
        const weightTrendData = await getPastFiveYearGoodsTypeWeight(defaultGoodsTypeId, selectedDateType.value);
        if (weightTrendData) {
          if (weightTrendData.result && Array.isArray(weightTrendData.result)) {
            weightLastSevenGoodsData.value = weightTrendData.result;
          } else if (Array.isArray(weightTrendData)) {
            weightLastSevenGoodsData.value = weightTrendData;
          }
        }
        updateSecondLineChart(weightLastSevenGoodsData.value);
      } else {
        console.warn('没有可用的货物类型数据');
        updateLineChart([]);
      }

    } catch (error) {
      console.error('获取数据失败:', error);
    } finally {
      // 设置为加载完成状态
      loading.value = false;
    }
    
    // 确保DOM更新后仍然保持选中状态
    setTimeout(() => {
      if (goodsTypeOptions.value.length > 0 && selectedGoodsType.value === null) {
        selectedGoodsType.value = goodsTypeOptions.value[0].value;
        currentGoodsTypeId.value = goodsTypeOptions.value[0].value;
        console.log('超时后设置默认选中的货物类型');
      }
    }, 100);

    
    // 检查是否有有效的价格数据
    const hasValidPriceData = priceLastSevenGoodsData.value.some(item => 
      item.goodsPrice !== null && item.goodsPrice !== undefined && item.goodsPrice > 0
    );
    
    // 按商品名称分组数据
    const goodsGroupMap = new Map<string, {dateStr: string, goodsPrice: number}[]>();
    
    // 遍历数据进行分组
    priceLastSevenGoodsData.value.forEach(item => {
      if (!goodsGroupMap.has(item.year)) {
        goodsGroupMap.set(item.year, []);
      }
      goodsGroupMap.get(item.year)?.push(item);
    });
    
    // 获取所有日期并进行处理
    // 不使用日期解析进行排序，直接使用原始顺序或简单的字符串排序
    // 因为接口已经在dataStr字段中返回了预格式化的内容
    const allDates = [...new Set(priceLastSevenGoodsData.value.map(item => item.dateStr))];
    // 如果确实需要排序，可以使用简单的字符串排序
    // 或者如果是特定格式（如2024-01, 2024-02等），可以保持原顺序
    
    // 定义颜色数组，用于不同商品的曲线
    const colors = [
      '#69c0ff', '#ff9c6e', '#5cdbd3', '#ff6700', 
      '#ff4500', '#006400', '#722ed1', '#13c2c2',
      '#faad14', '#52c41a', '#1890ff', '#eb2f96',
      '#ff7a45', '#597ef7', '#fa541c', '#13c2c2',
      '#2f54eb', '#722ed1', '#faad14', '#fadb14'
    ];
    
    // 创建series数据
    const seriesData = Array.from(goodsGroupMap.entries()).map(([goodsName, items], index) => {
      // 为每个日期找到对应的价格，如果没有则显示null（这样图表会跳过这些点）
      const data = allDates.map(date => {
        const item = items.find(i => i.dateStr === date);
        return item?.goodsPrice || null;
      });
      
      const color = colors[index % colors.length];
      
      return {
        name: goodsName,
        type: 'line' as const,
        yAxisIndex: 0,
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        data: data,
        lineStyle: {
          width: 3,
          color: color
        },
        itemStyle: {
          color: color
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: `${color}33` // 33是十六进制的51，约20%透明度
              },
              {
                offset: 1,
                color: `${color}0D` // 0D是十六进制的13，约5%透明度
              }
            ]
          }
        }
      };
    });
    
    // 如果没有有效数据，显示提示信息
    let finalSeriesData = seriesData;
    let finalDates = allDates;
    
    if (!hasValidPriceData) {
      finalDates = ['暂无数据'];
      // finalSeriesData = [
      //   {
      //     name: '暂无数据',
      //     type: 'line' as const,
      //     yAxisIndex: 0,
      //     smooth: true,
      //     symbol: 'circle',
      //     symbolSize: 8,
      //     data: [0],
      //     lineStyle: {
      //       width: 3,
      //       color: '#69c0ff'
      //     },
      //     itemStyle: {
      //       color: '#69c0ff'
      //     }
      //   }
      // ];
    }
    
    const lineOption = {
      title: {
        text: '近五年货物单价趋势',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params: any) => {
          let result = `${params[0].axisValue}<br/>`;
          params.forEach((param: any) => {
            result += `${param.marker}${param.seriesName}: ${param.value}<br/>`;
          });
          return result;
        }
      },
      legend: {
        data: finalSeriesData.map(series => series.name),
        top: '30px'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '80px',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: finalDates,
        axisLabel: {
          formatter: (value: string) => value
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '价格 (元)',
          nameTextStyle: {
            padding: [0, 0, 0, 0]
          },
          position: 'left',
          axisLabel: {
            formatter: '{value} 元'
          }
        }
      ],
      series: finalSeriesData
    };
    
    // 渲染曲线图
    setLineChartOptions(lineOption);
  });
</script>

<style lang="less" scoped></style>